package cn.ug.pay.pay.yeepay;

import java.util.Map;
import java.util.TreeMap;
import java.util.HashMap;

import cn.ug.config.YeePayConfig;
import cn.ug.pay.utils.RequestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 *  发起请求
 *  @auther ywl
 *  @date 2018-01-31 11:31:20
 */
@Component
public class TZTService {

	private static Logger logger = LoggerFactory.getLogger(TZTService.class);

	@Resource
	private YeePayConfig yeePayConfig;

	/**
	 * 格式化字符串
	 */
	public  String formatString(String text) {
		return (text == null ? "" : text.trim());
	}

	//加密
	public  String getSign(TreeMap<String,String> dataMap){
		String sign = EncryUtil.handleRSA(dataMap, yeePayConfig.getMerchantPrivateKey());
		return sign;
	}
	/**
	 * 解析http请求返回
	 */
	public  Map<String, String> parseHttpResponseBody(int statusCode, String responseBody) throws Exception {

		String merchantPrivateKey	= yeePayConfig.getMerchantPrivateKey();
		String yeepayPublicKey		= yeePayConfig.getYeepayPublicKey();

		Map<String, String> result	= new HashMap<String, String>();
		String customError			= "";

		if(statusCode != 200) {
			customError	= "Request failed, response code : " + statusCode;
			result.put("customError", customError);
			return (result);
		}

		Map<String, String> jsonMap	= JSON.parseObject(responseBody, 
											new TypeReference<TreeMap<String, String>>() {});

		if(jsonMap.containsKey("errorcode")) {
			result	= jsonMap;
			return (result);
		}

		String dataFromYeepay		= formatString(jsonMap.get("data"));
		String encryptkeyFromYeepay	= formatString(jsonMap.get("encryptkey"));

		boolean signMatch = EncryUtil.checkDecryptAndSign(dataFromYeepay, encryptkeyFromYeepay, 
										yeepayPublicKey, merchantPrivateKey);
		if(!signMatch) {
			customError	= "Sign not match error";
			result.put("customError",	customError);
			return (result);
		}

		String yeepayAESKey		= RSA.decrypt(encryptkeyFromYeepay, merchantPrivateKey);
		String decryptData		= AES.decryptFromBase64(dataFromYeepay, yeepayAESKey);

		result	= JSON.parseObject(decryptData, new TypeReference<TreeMap<String, String>>() {});

		return(result);
	}

	/**
	 * decryptCallbackData() : 解密支付回调参数data
	 *
	 */

	public  Map<String, String> decryptCallbackData(String data, String encryptkey) {

		logger.info("##### 解密返回数据 #####");
		
		String merchantaccount		= yeePayConfig.getMerchantAccount();
		String merchantPrivateKey	= yeePayConfig.getMerchantPrivateKey();
		String merchantAESKey		= RequestUtil.getMerchantAESKey();
		String yeepayPublicKey		= yeePayConfig.getYeepayPublicKey();

		logger.info("data : " + data);
		logger.info("encryptkey : " + encryptkey);
		
		Map<String, String> callbackResult	= new HashMap<String, String>();
		String customError			= "";
		
		try {
			boolean signMatch = EncryUtil.checkDecryptAndSign(data, encryptkey, yeepayPublicKey, merchantPrivateKey);

			if(!signMatch) {
				customError	= "Sign not match error";
				callbackResult.put("customError",	customError);
				return callbackResult;
			}

			String yeepayAESKey	= RSA.decrypt(encryptkey, merchantPrivateKey);
			String decryptData	= AES.decryptFromBase64(data, yeepayAESKey);
			callbackResult		= JSON.parseObject(decryptData, new TypeReference<TreeMap<String, String>>() {});

		} catch(Exception e) {
			customError		= "Caught an Exception. " + e.toString();
			callbackResult.put("customError", customError);
			e.printStackTrace();
		}

		System.out.println("callbackResult : " + callbackResult);

		return (callbackResult);
	}
	/**
	 * 取得商户AESKey
	 */
	public static String getMerchantAESKey() {
		return (RandomUtil.getRandom(16));
	}

}
